//
//  THJMainController.m
//  THJXHW
//
//  Created by 河南德艺 on 2017/9/9.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJMainController.h"
#import "JXSegment.h"
#import "JXPageView.h"
#import "THJMainTableViewCell.h"
#import "THJDataDetailVC.h"
#import "THJHejinMapVC.h"
#import <MJRefresh.h>
#import "ZBNetworking.h"

@interface THJMainController ()<UITableViewDelegate,UIAlertViewDelegate,UITableViewDataSource,JXSegmentDelegate,JXPageViewDataSource,JXPageViewDelegate>{
    JXPageView *pageView;
    JXSegment *segment;
    UITableView * _tableview;
    NSInteger  updownType;
    //滑动选中的菜单类型 1 2 3 4 5 6
    NSInteger  type;
    NSMutableArray * titleArr;
    NSString * updateTime;
    NSInteger highPrice;
    NSInteger lowPrice;
    NSInteger highIndex;
    NSInteger lowIndex;
}
@property(nonatomic,strong) NSArray *channelArray;
@property(nonatomic,strong) NSMutableArray *mainDataArray;
@property (weak, nonatomic) IBOutlet UIButton *reloadBtn;
@property(nonatomic,strong) NSMutableArray *qhDataArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@end
@implementation THJMainController
-(NSMutableArray*)qhDataArray{
    if (!_qhDataArray) {
        _qhDataArray = [[NSMutableArray alloc] init];
    }
    return _qhDataArray;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [[LBTabBarController sharedTabBarC].fabuView removeFromSuperview];
}
-(void)viewWillAppear:(BOOL)animated{
//    [[LBTabBarController sharedTabBarC].fabuView removeFromSuperview];
    [super viewWillAppear:animated];
    [self setStateBarColor:COLOR(83, 84, 85, 1)];
    [self.navigationController setNavigationBarHidden:YES animated:nil];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self SVHUDShow];
    self.reloadBtn.hidden = YES;
    [self updateVersion];
    updownType = 1;
    type = 1;
    [self getTitleNetData];
    [self getMainDataWithTypeId:@"1"];
   
    if(KIsiPhoneX){
        self.topSpace.constant = 95;
    }
    self.view.backgroundColor = COLOR(34, 34, 34, 1);
}
//点击重试
- (IBAction)reloadData:(id)sender {
//    [self updateVersion];
    updownType = 1;
    type = 1;
    [self getTitleNetData];
    [self getMainDataWithTypeId:@"1"];
    [self SVHUDShow];
}
/**
    获取现货数据
 @param typeId 类型
 */
-(void)getMainDataWithTypeId:(NSString*)typeId{
    __weak typeof(self) weekself = self;
    NSString * urlstr = [NSString stringWithFormat:@"http://read.thjb.net/index.php?action=app_hjb_now&type=%@",typeId];
    NSLog(@"指数url-%@",urlstr);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=urlstr;
        request.apiType=ZBRequestTypeRefresh;
    }  success:^(id responseObject,apiType type){
        [weekself SVHUDHiden];
//        NSLog(@"redata-%@",responseObject);
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [_tableview.mj_header endRefreshing];
        if([receiveData[@"status"] isEqual:@"success"]){
            updateTime = receiveData[@"data"][@"date"];
            weekself.mainDataArray = receiveData[@"data"][@"list"];
            [_tableview reloadData];
            NSLog(@"HI-%ld--%ld",highPrice,lowPrice);
        }else{
            [weekself HUDShowMsg:@"加载出错" AfterDelayDimiss:2];
             weekself.reloadBtn.hidden = NO;
        }
    } failed:^(NSError *error){
        [weekself SVHUDHiden];
        [weekself HUDShowMsg:@"加载失败" AfterDelayDimiss:2];
        weekself.reloadBtn.hidden = NO;
        NSLog(@"error-%@",error);
    }];
}
/**
 获取滚动标题数据
 */
-(void)getTitleNetData{
    
    NSString * urlstr = @"http://read.thjb.net/index.php?action=app_zhishu_type";
    [THJNetWork getNetDataFromUrl:urlstr callback:^(NSDictionary* receiveData, NSError *error) {
        if(!error){
            if(receiveData[@"status"]){
                titleArr = receiveData[@"data"];
                [self setSegmentControlWithNameArr:titleArr];
            }
        }
    }];
}
-(void)setSegmentControlWithNameArr:(NSArray*)array{
    CGFloat space;
    if(KIsiPhoneX){
        space = 40;
    }else{
        space = 20;
    }
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, space)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    UIView * logoView = [[UIView alloc] initWithFrame:CGRectMake(0, space - 1, 35, 45)];
    logoView.backgroundColor = MainColor;
    [self.view addSubview:logoView];
    
    UIImageView * logoImgV = [[UIImageView alloc] initWithImage:kGetImage(@"logoPic")];
    logoImgV.frame = CGRectMake(0, 5, 35, 35);
    logoImgV.backgroundColor = MainColor;
    [logoView addSubview:logoImgV];
    
    UIView * searchView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth-50, space, 50, 44.5)];
    searchView.backgroundColor =COLOR(83, 84, 85, 1);
    [self.view addSubview:searchView];
    
    UIButton * mapBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [mapBtn setBackgroundImage:kGetImage(@"positionOrange") forState:UIControlStateNormal];
    mapBtn.frame = CGRectMake(12.5, 7, 25, 25);
    [mapBtn addTarget:self action:@selector(mapBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:mapBtn];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    segment = [[JXSegment alloc] initWithFrame:CGRectMake(35, space, ScreenWidth-85, 45)];
    segment.scrollView.backgroundColor = COLOR(83, 84, 85, 1);
    [segment updateChannels:array];
    
    segment.delegate = self;
    [self.view addSubview:segment];
    CGFloat height;
    CGFloat constant;
    if(KIsiPhoneX){
        height = 115;
        constant = 60;
    }else{
        height = 87;
        constant = 0;
    }
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, height, ScreenWidth, ScreenHeight-90-49- constant) style:UITableViewStylePlain];
    [_tableview registerNib:[UINib nibWithNibName:@"THJMainTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [_tableview  setSeparatorColor:COLOR(77, 77,77, 1)];
    _tableview.backgroundColor = COLOR(34, 34, 34, 1);
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downUpdate)];
    _tableview.delegate = self;
    _tableview.rowHeight = 60;
    _tableview.dataSource = self;
    _tableview.tableFooterView = [UIView new];
    [self.view addSubview:_tableview];
}
/**
 下拉刷新
 */
-(void)downUpdate{
    [self getMainDataWithTypeId:[NSString stringWithFormat:@"%ld",type]];
}
/**
 涨跌按钮点击 涨跌的类型  数值或百分比 1 数值  2 百分比
 */
- (IBAction)upDownAction:(UIButton*)sender{
    if(updownType == 1){
        [sender setTitle:@"涨幅(%)"forState:UIControlStateNormal];
        updownType = 2;
    }else{
        [sender setTitle:@"涨跌"forState:UIControlStateNormal];
        updownType = 1;
    }
    [_tableview reloadData];
}

/**
 地图按钮点击
 */
-(void)mapBtnAction{
    [self.navigationController pushViewController:[THJHejinMapVC new] animated:YES];
}
#pragma mark - tableviewdelegate --

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.mainDataArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    THJMainTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(self.mainDataArray.count>0){
        
        [cell updateCellContentWidthDic:self.mainDataArray[indexPath.row] UpdownType:updownType btnFlag:1];
       
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    THJDataDetailVC * vc= [[THJDataDetailVC alloc] init];
    vc.updateTime = updateTime;
    vc.dataInfo = self.mainDataArray[indexPath.row];
    vc.titleStr = titleArr[type - 1];
    vc.itemType = [NSString stringWithFormat:@"%ld",type];
    vc.areaId = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - JXPageViewDataSource
-(NSInteger)numberOfItemInJXPageView:(JXPageView *)pageView{
    return self.channelArray.count;
}
-(UIView*)pageView:(JXPageView *)pageView viewAtIndex:(NSInteger)index{
    UIView *view = [[UIView alloc] init];
    return view;
}
#pragma mark - JXSegmentDelegate
-(void)JXSegment:(JXSegment*)segment didSelectIndex:(NSInteger)index{
    NSLog(@"index--%ld",index);
    //如果期货按钮是选中状态 那么不变
    if(type != index+1){
        type = index+1;
        [self getMainDataWithTypeId:[NSString stringWithFormat:@"%ld",index+1]];
    }
}

#pragma mark - JXPageViewDelegate -
- (void)didScrollToIndex:(NSInteger)index{
    [segment didChengeToIndex:index];
     NSLog(@"**-%ld",(long)index);
}
/**
    提示版本更新
 */
-(void)updateVersion{
    NSString *version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
    NSArray * nowArr = [version componentsSeparatedByString:@"."];
    NSLog(@"nowversion-%@",version);
    __weak typeof(self) weakself = self;
    NSString * url = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"version.php?action=update&way=ios"];
    [THJNetWork getNetDataFromUrl:url callback:^(NSDictionary* receiveData, NSError *error) {
        if (receiveData) {
            if(receiveData[@"vname"]){
                NSArray  * newArr = [receiveData[@"vname"] componentsSeparatedByString:@"."];
                if ([newArr[0] integerValue] > [nowArr[0] integerValue]) {
                    [weakself updateVersionShowWithContent:receiveData[@"vcontent"]];
                    return;
                }else if ([newArr[0] integerValue] == [nowArr[0] integerValue]){
                    if ([newArr[1] integerValue] > [nowArr[1] integerValue]){
                        [weakself updateVersionShowWithContent:receiveData[@"vcontent"]];
                    }else if ([newArr[1] integerValue] == [nowArr[1] integerValue]) {
                        if ([newArr[2] integerValue] > [nowArr[2] integerValue]){
                            [weakself updateVersionShowWithContent:receiveData[@"vcontent"]];
                        }
                    }
                }
            }
        }
    }];
}
-(void)updateVersionShowWithContent:(NSString*)content{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发现新版本" message:content delegate:self cancelButtonTitle:@"下次再说" otherButtonTitles:@"前往更新", nil];
    alert.delegate = self;
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        NSLog(@"1");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/%E9%93%81%E5%90%88%E9%87%91%E7%8E%B0%E8%B4%A7%E7%BD%91/id1179909421?mt=8"]];
    }
}
@end
